define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'vue'], function($, undefined, Backend,Table, Form, Vue) {
    var Controller = {
        index: function() {
            //查看推广码
            $(document).on('click', 'a[data-class="promotion_qr_data"]', function(){
                var url = 'api/wanlshop/common/mpQrcode?data='+$(this).data('promotion_qr_data');
                //alert(url);
                layer.open({
                    type: 1, // 页面层
                    area: ['300px', '300px'], // 弹窗大小自适应
                    title: false, // 不显示标题栏
                    closeBtn: 1, // 显示关闭按钮
                    shade: 0.5, // 遮罩层透明度
                    content: '<img src="/'+url+'" width="300" hide="300">'
                });
            });
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'wanlshop/goods/index' + location.search,
                    add_url: 'wanlshop/goods/add',
                    edit_url: 'wanlshop/goods/edit',
                    reuse_url: 'wanlshop/goods/reuse',
                    del_url: 'wanlshop/goods/del',
                    multi_url: 'wanlshop/goods/multi',
                    resubmit_url: 'wanlshop/goods/resubmit',
                    dragsort_url: "",
                    table: 'wanlshop_goods',
                }
            });

            var table = $("#table");
            $(".btn-add").data("area", ["100%", "100%"]);

            $(document).on("click", ".goods-shop-type-item", function () {
                $(".active-type").removeClass('active-type');
                $(this).addClass('active-type');
                window.location =  $(this).data('url');
            });

            $(document).on("click", ".btn-resubmit", function () {
                var ids = Table.api.selectedids(table);
                Fast.api.open("wanlshop/goods/resubmit/ids/" + ids, __('批量铺设'), {
                    area: ['800px', '500px']
                });
            });

            $(document).on("click", ".btn-batch", function () {
                var ids = Table.api.selectedids(table);
                Fast.api.open("wanlshop/goods/batch/ids/" + ids, __('批量下架'), {
                    area: ['800px', '500px']
                });
            });

            $(document).on('click', '.btn-batchprice', function() {
                var ids = Table.api.selectedids(table);
                if (ids.length == 0) {
                    Layer.msg("请选择要修改的商品");
                    return;
                }

                selectShopModal(ids);
            });

            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                    $(".btn-editone").data("area", ["100%", "100%"]);
             });

            table.on('post-common-search.bs.table', function (event, table) {
                $('ul.nav-tabs li a[data-value="normal"]').trigger('click');
                $(".form-commonsearch select[name=status]").val("normal");
            });
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                Search:true,
                commonSearch:true,
                searchFormVisible:true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id',title: __('Id') ,operate: false},
                        // {field: 'code',title: __('商品编号') ,operate: 'like'},
                        {field: 'title',title: __('Title'),operate: 'like'},
                        {field: 'promotion_qr_data', title: __('推广码'), align: 'center', formatter:function(value, row, index){
                            return '<a href="javascript:void(0)" class="btn btn-xs btn-success" data-class="promotion_qr_data" data-promotion_qr_data="'+value+'">查看</a>';
                        }},

                        {field: 'selfsupport',title: __('门店自建'),searchList: {"0": __('否'),"1": __('是')},formatter: Table.api.formatter.status},
                        {field: 'image',title: __('Image'),events: Table.api.events.image,formatter: Table.api.formatter.image,operate: false},
                        // {field: 'shop_category_id', title: __('Shop_category_id'), operate:'RANGE', visible: false,operate: false},
                        {field: 'category.name', title: __('商品分类'), formatter: Table.api.formatter.search,operate:false},
                        {field: 'category.id', title: __('商品分类'), searchList: $.getJSON('ajax/getgoodscategorylist'),formatter: Table.api.formatter.search,visible:false},
                       // {field: 'title',title: __('Title')},
                        {field: 'channel',title: __('channel'),searchList: {"0": __('All'),"1": __('线上'),"2": __('线下')},formatter: Table.api.formatter.status,operate: false},
                        {field: 'grounding',title: __('Status'),searchList: {"1": __('Top_line'),"0": __('down_line')},formatter: Table.api.formatter.status},
                        // {field: 'image',title: __('Image'),events: Table.api.events.image,formatter: Table.api.formatter.image},
                        // {field: 'images',title: __('Images'),events: Table.api.events.image,formatter: Table.api.formatter.images},
                        // {field: 'flag',title: __('Flag'),searchList: {"hot": __('Flag hot'),"index": __('Flag index'),"recommend": __('Flag recommend')},operate: 'FIND_IN_SET',formatter: Table.api.formatter.label},
                      //  {field: 'shopsort.name', title: __('Shopsort.name'), formatter: Table.api.formatter.search},
                        {field: 'price',title: __('Price'),operate: false},
                        {field: 'vip_price',title: __('会员价'),operate: false},
                        {field: 'on_sale_shop',title: __('在售门店'),operate: false,
                            formatter: function(value, row, index) {
                                // 生成带点击事件的链接，传递商品ID
                                return '<a href="javascript:;" class="btn btn-xs btn-primary js-view-shops" data-id="' + row.id + '">' + value + ' 家店铺</a>';
                            }
                        },
                        // {field: 'distribution',title: __('Distribution'),searchList: {"true": __('Distribution true'),"false": __('Distribution false')},formatter: Table.api.formatter.normal},
                        // {field: 'activity',title: __('Activity'),searchList: {"true": __('Activity true'),"false": __('Activity false')},formatter: Table.api.formatter.normal},
                        {field: 'stocks',title: __('库存'),operate: false},
                        {field: 'sales',title: __('Sales'),operate: false},
                      //  {field: 'comment',title: __('Comment')},
                        // {field: 'praise',title: __('Praise')},
                        // {field: 'like',title: __('Like')},{field: 'createtime',title: __('Createtime'),operate: 'RANGE',addclass: 'datetimerange',formatter: Table.api.formatter.datetime},
                        // {field: 'updatetime',title: __('Updatetime'),operate: 'RANGE',addclass: 'datetimerange',formatter: Table.api.formatter.datetime},
                        // {field: 'operate',title: __('Operate'),table: table, events: Table.api.events.operate,formatter: Table.api.formatter.operate}
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            buttons :[
                                /*{
                                    name: 'promotion',
                                    text: '推广码',
                                    title: '推广码',
                                    icon: '',
                                    extend: 'data-class="promotion" data-promotion_qr_data="'+row.promotion_qr_data+'"',
                                    classname: 'btn btn-xs btn-success'
                                },*/
                                {
                                    name: 'resubmit',
                                    text: '铺设',
                                    title: '铺设',
                                    icon: '',
                                    extend: 'data-area=\'["80%", "80%"]\'',
                                    classname: 'btn btn-xs btn-danger btn-dialog',
                                    url: "wanlshop/goods/resubmit",
                                    hidden:function(row){
                                        if(row.show_copy == 0){
                                            return true;
                                        }else{
                                            return false;
                                        }
                                    },
                                },
                                {
                                    name: 'reuse',
                                    text: '复制',
                                    title: '复制',
                                    icon: '',
                                    extend: 'data-area=\'["80%", "80%"]\'',
                                    classname: 'btn btn-xs btn-warning btn-dialog',
                                    url: "wanlshop/goods/reuse",
                                },
                            ],
                            callback: function (data) {
                                table.bootstrapTable('refresh', {});
                                return false;
                            },
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            $(document).on('click', '.js-view-shops', function() {
                var goodsId = $(this).data('id');
                loadShopList(goodsId, 1); // 加载第一页数据
            });

            // 加载店铺列表数据
            function loadShopList(goodsId, page) {
                // 显示加载状态
                $('.loading').removeClass('hide');
                $('.table-responsive, #sublistEmpty').addClass('hide');
                
                // 发送AJAX请求
                $.ajax({
                    url: 'wanlshop/goods/onsaleshops', // 后端接口URL
                    method: 'GET',
                    data: {
                        id: goodsId,
                        page: page,
                        limit: 10 // 每页10条数据
                    },
                    success: function(res) {
                        if (res.code === 0) {
                            renderShopList(res);
                            renderPagination(res, goodsId);
                            updatePaginationInfo(res);
                            $('#sublistModal').modal('show');
                        } else {
                            Layer.msg(res.msg || '获取数据失败', {icon: 2});
                        }
                    },
                    error: function() {
                        Layer.msg('网络请求失败', {icon: 2});
                    },
                    complete: function() {
                        $('.loading').addClass('hide');
                    }
                });
            }

            // 渲染店铺列表
            function renderShopList(res) {
                var tbody = $('#sublistBody');
                tbody.empty();
                
                if (res.data && res.data.length > 0) {
                    res.data.forEach(function(item) {
                        var tr = $('<tr>');
                        tr.append('<td>' + item.id + '</td>');
                        tr.append('<td>' + item.shopname + '</td>');
                        tr.append('<td>' + item.person + '</td>');
                        tr.append('<td>' + item.telephone + '</td>');
                        tr.append('<td>' + item.adds + '</td>');
                        tbody.append(tr);
                    });
                    $('.table-responsive').removeClass('hide');
                    $('#sublistEmpty').addClass('hide');
                } else {
                    $('.table-responsive').addClass('hide');
                    $('#sublistEmpty').removeClass('hide');
                }
            }

            // 更新分页信息显示
            function updatePaginationInfo(res) {
                const start = ((res.current_page - 1) * res.per_page) + 1;
                const end = Math.min(res.current_page * res.per_page, res.total);
                
                const infoText = `
                    <span class="text-sm text-gray-700">
                        显示 <span class="font-medium">${start}</span> 到 <span class="font-medium">${end}</span> 条，
                        共 <span class="font-medium">${res.total}</span> 条记录
                    </span>
                `;
                
                $('#paginationInfo').html(infoText);
            }

            // 渲染分页控件
            function renderPagination(res, goodsId) {
                const pagination = $('#sublistPagination');
                pagination.empty();
                
                const currentPage = res.current_page;
                const lastPage = res.last_page;
                const baseUrl = 'javascript:void(0)';
                
                // 如果只有一页或没有数据，不显示分页控件
                if (lastPage <= 1 || res.total === 0) {
                    $('.pagination-container').addClass('hidden');
                    return;
                } else {
                    $('.pagination-container').removeClass('hidden');
                }
                
                // 添加上一页按钮
                const prevDisabled = currentPage === 1;
                const prevButton = `
                    <li class="page-item ${prevDisabled ? 'opacity-50 cursor-not-allowed' : ''}">
                        <a class="page-link flex items-center justify-center w-10 h-10 rounded-lg border border-gray-300 bg-white text-gray-500 transition-all duration-200" 
                           href="${baseUrl}" 
                           data-page="${currentPage - 1}" 
                           data-id="${goodsId}"
                           ${prevDisabled ? 'onclick="return false;" disabled' : ''}>
                            <i class="fa fa-chevron-left text-xs"></i>
                        </a>
                    </li>
                `;
                pagination.append(prevButton);
                
                // 显示第一页（如果当前页不是第一页且距离第一页超过2页）
                if (currentPage > 3) {
                    appendPageButton(1, goodsId, currentPage);
                    
                    // 添加省略号
                    if (currentPage > 4) {
                        pagination.append(`
                            <li class="page-item disabled">
                                <span class="page-link flex items-center justify-center w-10 h-10 text-gray-400">...</span>
                            </li>
                        `);
                    }
                }
                
                // 显示当前页附近的页码
                let startPage = Math.max(1, currentPage - 2);
                let endPage = Math.min(lastPage, currentPage + 2);
                
                for (let i = startPage; i <= endPage; i++) {
                    appendPageButton(i, goodsId, currentPage);
                }
                
                // 显示最后一页（如果当前页不是最后一页且距离最后一页超过2页）
                if (currentPage < lastPage - 2) {
                    // 添加省略号
                    if (currentPage < lastPage - 3) {
                        pagination.append(`
                            <li class="page-item disabled">
                                <span class="page-link flex items-center justify-center w-10 h-10 text-gray-400">...</span>
                            </li>
                        `);
                    }
                    
                    appendPageButton(lastPage, goodsId, currentPage);
                }
                
                // 添加下一页按钮
                const nextDisabled = currentPage === lastPage;
                const nextButton = `
                    <li class="page-item ${nextDisabled ? 'opacity-50 cursor-not-allowed' : ''}">
                        <a class="page-link flex items-center justify-center w-10 h-10 rounded-lg border border-gray-300 bg-white text-gray-500 transition-all duration-200" 
                           href="${baseUrl}" 
                           data-page="${currentPage + 1}" 
                           data-id="${goodsId}"
                           ${nextDisabled ? 'onclick="return false;" disabled' : ''}>
                            <i class="fa fa-chevron-right text-xs"></i>
                        </a>
                    </li>
                `;
                pagination.append(nextButton);
                
                // 绑定分页按钮点击事件
                $('.page-link:not([disabled])').click(function() {
                    const page = $(this).data('page');
                    const id = $(this).data('id');
                    loadShopList(id, page);
                });
            }

            // 辅助函数：添加页码按钮
            function appendPageButton(pageNum, goodsId, currentPage) {
                const isActive = pageNum === currentPage;
                const pagination = $('#sublistPagination');
                
                const buttonClass = isActive 
                    ? 'bg-primary text-white border-primary shadow-md curr-item hover:bg-primary/90' 
                    : 'bg-white text-gray-700 border border-gray-300 hover:bg-gray-50';
                
                pagination.append(`
                    <li class="page-item">
                        <a class="page-link flex items-center justify-center w-10 h-10 rounded-lg ${buttonClass} transition-all duration-200" 
                           href="javascript:void(0)" 
                           data-page="${pageNum}" 
                           data-id="${goodsId}"
                           ${isActive ? 'onclick="return false;" disabled' : ''}>
                            ${pageNum}
                        </a>
                    </li>
                `);
            }

            //批量改价相关事件
            // 店铺选择模态框
            function selectShopModal(goodsIds) {
                // 使用FastAdmin的modal方法弹出店铺选择框
                Fast.api.open("wanlshop/goods/shoplist", __('选择店铺'), 
                {
                    area: ['90%', '90%'],
                    callback: function(data) {
                        if (data && data.shop_ids && data.shop_ids.length > 0) {
                            setPriceModal(goodsIds, data.shop_ids);
                        }
                    }
                }
                );
            }

            // 价格设置模态框
            function setPriceModal(goodsIds, shopIds) {
                // 创建价格设置表单
                var formHtml = '<div class="form-group">' +
                                '<label for="price" class="control-label col-xs-12 col-sm-3">价格</label>' +
                                '<div class="col-xs-12 col-sm-9">' +
                                '<input type="number" class="form-control" id="goodsprice" name="goodsprice" min="0" step="0.01" required>' +
                                '<p class="help-block">请输入新的商品价格</p>' +
                                '</div>' +
                                '</div>'+ 
                                '<div class="form-group">' +
                                '<label for="price" class="control-label col-xs-12 col-sm-3">名称</label>' +
                                '<div class="col-xs-12 col-sm-9">' +
                                '<input type="text" class="form-control" id="goodstitle" name="goodstitle" required>' +
                                '<p class="help-block">请输入新的商品名称</p>' +
                                '</div>' +
                                '</div>';
                
                // 弹出价格设置模态框，并保存其索引
                var modalIndex = Layer.open({
                    title: '设置商品信息',
                    content: formHtml,
                    btn: ['确定', '取消'],
                    area: ['40%', '30%'],
                    yes: function(index, layero) {
                        var price = $('#goodsprice').val();
                        var title = $('#goodstitle').val();
                        if (!price) {
                            // 显示错误提示，但不关闭价格设置模态框
                            layer.msg('价格不能为空', {
                                icon: 2, // 使用错误图标
                                time: 2000 // 2秒后自动关闭提示
                                // 不需要end回调，因为我们不想关闭价格设置模态框
                            });
                            return false; // 阻止关闭价格设置模态框
                        }
                        
                        // 显示加载状态
                        var loadingIndex = layer.load(1, {
                            shade: [0.1,'#fff'] // 0.1透明度的白色背景
                        });

                        // 发送请求到后台处理
                        updateGoodsPrice(goodsIds, shopIds, price, title, function(success, message) {
                            // 无论成功或失败，都关闭加载状态
                            layer.close(loadingIndex);
                            
                            if (success) {
                                layer.msg(message || '价格更新成功', {icon: 1, time: 1500});
                                Layer.close(modalIndex); // 关闭价格设置模态框
                            } else {
                                layer.msg(message || '价格更新失败', {icon: 2, time: 2000});
                            }
                        });
                        $("a.btn-refresh").trigger("click");     
                        return false; // 阻止默认关闭行为，等待回调处理
                    }
                });
            }

            function updateGoodsPrice(goodsIds, shopIds, price,title, callback) {
                Fast.api.ajax({
                    url: 'wanlshop/goods/batchUpdatePrice',
                    data: {
                        goods_ids: goodsIds,
                        shop_ids: shopIds,
                        price: price,
                        title: title
                    }
                }, function(data, ret) {
                    if (callback) callback(true, ret.msg);
                    return false;
                }, function(data, ret) {
                    if (callback) callback(false, ret.msg);
                    return false;
                });
            }

            // 为表格绑定事件
            Table.api.bindevent(table);
            // table.on('load-success.bs.table',function(data){
            //     $(".btn-editone").data("area", ["90%","80%"]);
            //     $(".btn-add").data("area", ["90%","80%"]);
            // });
        },
        shoplist: function () {
            var goods_id = Config.goods_id;
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'wanlshop/goods/shoplist' + location.search,
                    table: 'wanlshop_shop',
                }
            });

            var table = $("#table");

            $(".btn-add").data("area", ["100%", "100%"]);

            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                    $(".btn-editone").data("area", ["100%", "100%"]);
             });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                fixedColumns: true,
                fixedRightNumber: 1,
                searchFormVisible:false,
                search:false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'),visible:false, operate: false},
                        {field: 'shopname', title: __('商家名称'), operate: 'LIKE'},
                        {field: 'type', title: __('商家分类'), searchList: {"0":__('直营店'),"1":__('加盟店'),"2":__('社区单店')}, operate: false,formatter: Table.api.formatter.normal},
                        {field: 'person', title: __('联系人'), operate: 'LIKE', operate: false},
                        {field: 'telephone', title: __('联系方式'), operate: 'LIKE', operate: false},
                        {field: 'city', title: __('所属地区'), operate: 'LIKE', operate: false},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime, operate: false},
                        {field: 'status', title: __('Status'), searchList: {"normal":__('营业中'),"hidden":__('下线')}, formatter: Table.api.formatter.status, operate: false}
                    ]
                ]
            });

            $("button[type='submit']").css("background-color","red");
            $("button[type='submit']").css("border-color","red");

            //保存设置
            $(document).on("click", ".choose-shop", function () {
                var ids = Table.api.selectedids(table);
                if (ids.length == 0) {
                    layer.msg("请选择要设置的店铺！");
                }

                Fast.api.close({shop_ids: ids});
            });
            
            
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        // shoplist:function(){
        //     // 全选功能
        //     // $('#check-all-shop').on('ifChanged', function() {
        //     //     $('input[name="shop_ids[]"]').iCheck(this.checked ? 'check' : 'uncheck');
        //     // });
            
        //     // 原生 jQuery 实现全选功能
        //     $('#check-all-shop').on('change', function() {
        //         $('input[name="shop_ids[]"]').prop('checked', this.checked);
        //     });

        //     // 单个复选框事件
        //     $('input[name="shop_ids[]"]').on('change', function() {
        //         var allChecked = $('input[name="shop_ids[]"]').length === $('input[name="shop_ids[]"]:checked').length;
        //         $('#check-all-shop').prop('checked', allChecked);
        //     });

        //     // 确认选择按钮
        //     $('#confirm-select-shops').on('click', function() {
        //         var shopIds = [];
        //         $('input[name="shop_ids[]"]:checked').each(function() {
        //             shopIds.push($(this).val());
        //         });
                
        //         if (shopIds.length === 0) {
        //             layer.msg('请选择至少一个店铺');
        //             return;
        //         }
                
        //         Fast.api.close({shop_ids: shopIds});
        //     });
        // },
        stock: function() {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'wanlshop/goods/index' + location.search,
                    add_url: 'wanlshop/goods/add',
                    edit_url: 'wanlshop/goods/edit',
                    del_url: 'wanlshop/goods/del',
                    multi_url: 'wanlshop/goods/multi',
                    dragsort_url: "",
                    table: 'wanlshop_goods',
                }
            });
            var table = $("#table");

            table.on('post-common-search.bs.table', function (event, table) {
                $('ul.nav-tabs li a[data-value="hidden"]').trigger('click');
                $(".form-commonsearch select[name=status]").val("hidden");
            });
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id',title: __('Id')},
                        {field: 'category.name', title: __('Category.name'), formatter: Table.api.formatter.search},
                        {field: 'title',title: __('Title')},
                        {field: 'image',title: __('Image'),events: Table.api.events.image,formatter: Table.api.formatter.image},
                        {field: 'images',title: __('Images'),events: Table.api.events.image,formatter: Table.api.formatter.images},
                        // {field: 'flag',title: __('Flag'),searchList: {"hot": __('Flag hot'),"index": __('Flag index'),"recommend": __('Flag recommend')},operate: 'FIND_IN_SET',formatter: Table.api.formatter.label},
                        {field: 'shopsort.name', title: __('Shopsort.name'), formatter: Table.api.formatter.search},
                        {field: 'price',title: __('Price'),operate: 'BETWEEN'},
                        // {field: 'distribution',title: __('Distribution'),searchList: {"true": __('Distribution true'),"false": __('Distribution false')},formatter: Table.api.formatter.normal},
                        // {field: 'activity',title: __('Activity'),searchList: {"true": __('Activity true'),"false": __('Activity false')},formatter: Table.api.formatter.normal},
                        {field: 'views',title: __('Views')},{field: 'sales',title: __('Sales')},{field: 'comment',title: __('Comment')},{field: 'praise',title: __('Praise')},
                        {field: 'like',title: __('Like')},{field: 'createtime',title: __('Createtime'),operate: 'RANGE',addclass: 'datetimerange',formatter: Table.api.formatter.datetime},
                        {field: 'updatetime',title: __('Updatetime'),operate: 'RANGE',addclass: 'datetimerange',formatter: Table.api.formatter.datetime},
                        {field: 'status',title: __('Status'),searchList: {"normal": __('Normal'),"hidden": __('Hidden')},formatter: Table.api.formatter.status},
                        {field: 'operate',title: __('Operate'),table: table,events: Table.api.events.operate,formatter: Table.api.formatter.operate}
                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function() {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });
            var table = $("#table");
            // 初始化表格
            table.bootstrapTable({
                url: 'wanlshop/goods/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [{
                        checkbox: true
                    },
                        {
                            field: 'id',
                            title: __('Id')
                        },
                        {
                            field: 'title',
                            title: __('Title'),
                            align: 'left'
                        },
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [{
                                name: 'Restore',
                                text: __('Restore'),
                                classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                icon: 'fa fa-rotate-left',
                                url: 'wanlshop/goods/restore',
                                refresh: true
                            },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'wanlshop/goods/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        select: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'wanlshop/goods/select',
                }
            });
            var idArr = [];
            var dataArr = [];
            var table = $("#table");

            table.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table', function (e, row) {
                if (e.type == 'check' || e.type == 'uncheck') {
                    row = [row];
                } else {
                    idArr = [];
                    dataArr = [];
                }
                $.each(row, function (i, j) {
                    if (e.type.indexOf("uncheck") > -1) {
                        var index = idArr.indexOf(j.id);
                        if (index > -1) {
                            idArr.splice(index, 1);
                            $.each(dataArr, function(key,value){
                                if(value.id == j.id){
                                    dataArr.splice(key, 1);
                                }
                            })
                        }
                    } else {
                        if(idArr.indexOf(j.id) == -1){
                            idArr.push(j.id);
                            dataArr.push({
                                id: j.id,
                                image: j.image,
                                price: j.price,
                                title: j.title
                            });
                        }
                    }
                });
            });

            // 初始化表格
            table.bootstrapTable({
                queryParams:function(params){
                    var filter = JSON.parse(params.filter);
                    var op = JSON.parse(params.op);
                    filter['publishing_platform'] = '0';
                    op['publishing_platform'] = '=';
                    params.filter = JSON.stringify(filter);
                    params.op = JSON.stringify(op);
                    return params;
                },
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                sortName: 'id',
                showToggle: false,
                showExport: false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'image', title: __('Image'), events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'title', title: __('Title')},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {
                            field: 'operate', title: __('Operate'), events: {
                                'click .btn-chooseone': function (e, value, row, index) {
                                    var multiple = Backend.api.query('multiple');
                                    multiple = multiple == 'true' ? true : false;
                                    Fast.api.close({url: row.id, data: [{
                                            id: row.id,
                                            image: row.image,
                                            price: row.price,
                                            title: row.title
                                        }], multiple: multiple});
                                },
                            }, formatter: function () {
                                return '<a href="javascript:;" class="btn btn-danger btn-chooseone btn-xs"><i class="fa fa-check"></i> ' + __('Choose') + '</a>';
                            }
                        }
                    ]
                ]
            });

            // 选中多个
            $(document).on("click", ".btn-choose-multi", function () {
                var multiple = Backend.api.query('multiple');
                multiple = multiple == 'true' ? true : false;
                Fast.api.close({
                    url: idArr.length == 0 ? '': idArr.join(","),
                    data: dataArr,
                    multiple: multiple
                });
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function() {
            var vm = new Vue({
                el: '#app',
                data() {
                    return {
                        spu: [],
                        spuItem: [],
                        sku: [],
                        skuImg: [],
                        batch: 0,
                        categoryId: '',
                        categoryList :Config.channelList,
                        categoryOne: null,
                        categoryTwo: null,
                        categoryThree: null,
                        categoryFour: null,
                        categoryFive: null,
                        attributeData: []
                    }
                },
                methods: {
                    // 页面上传图片 1.1.9升级
                    changeImage(event, key){
                        let files = event.target.files[0]; //获取input的图片file值
                        require(['upload'], function (Upload) {
                            Upload.api.send(files, function (data, ret) {
                                Vue.set(vm.skuImg, key, data.url);
                            });
                        });
                    },
                    getCategory(e){
                        if(e == 1){
                            this.categoryTwo = null;
                            this.categoryThree = null;
                            this.categoryFour = null;
                            this.categoryFive = null;
                        }
                        if(this.categoryOne != null){
                            this.categoryId = this.categoryList[this.categoryOne].id;
                        }
                        if(this.categoryTwo != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].id;
                        }
                        if(this.categoryThree != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].childlist[this.categoryThree].id;
                        }
                        if(this.categoryFour != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].childlist[this.categoryThree].childlist[this.categoryFour].id;
                        }
                        if(this.categoryFive != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].childlist[this.categoryThree].childlist[this.categoryFour].childlist[this.categoryFive].id;
                        }


                        // 查询类目属性
                        Fast.api.ajax("wanlshop.goods/attribute?id=" + this.categoryId, (data, ret) =>{
                            this.attributeData = data;
                            //返回false时将不再有右上角的操作成功的提示
                            return false;
                        });
                    },
                    // 添加属性
                    spuAdd(){
                        var str = this.$refs['specs-name'].value || ''
                        str = str.trim();
                        if (!str){
                            layer.msg("产品属性不能为空");
                            return
                        }
                        // 遍历
                        var arr = str.split(/\s+/);
                        for (var i=0;i<arr.length;i++)
                        {
                            this.spu.push(arr[i])
                        }
                        // 清空表单
                        this.$refs['specs-name'].value = ''
                    },
                    // 删除属性
                    spuRemove(key){
                        Vue.delete(vm.spuItem, key);
                        Vue.delete(vm.spu, key);
                        this.skuCreate();
                    },
                    // 添加规格
                    skuAdd(index) {
                        var str = this.$refs['specs-name-' + index][0].value || ''
                        str = str.trim();
                        if (!str){
                            layer.msg("产品属性不能为空")
                            return
                        }
                        // 遍历
                        var arr = str.split(/\s+/);
                        for (var i=0;i<arr.length;i++)
                        {
                            if (this.spuItem[index]) {
                                this.spuItem[index].push(arr[i])
                            } else {
                                this.spuItem.push([arr[i]])
                            }
                        }
                        // 清空表单
                        this.$refs['specs-name-' + index][0].value = ""
                        this.skuCreate();
                    },
                    // 删除规格
                    skuRemove(i,key){
                        Vue.delete(vm.spuItem[i], key);
                        this.skuCreate();
                    },
                    // 生成Sku
                    skuCreate() {
                        this.sku = this.skuDesign(this.spuItem)
                    },
                    skuDesign(array) {
                        if (array.length == 0) return []
                        if (array.length < 2) {
                            var res = []
                            array[0].forEach(function(v) {
                                res.push([v])
                            })
                            return res
                        }
                        return [].reduce.call(array, function(col, set) {
                            var res = [];
                            col.forEach(function(c) {
                                set.forEach(function(s) {
                                    var t = [].concat(Array.isArray(c) ? c : [c]);
                                    t.push(s);
                                    res.push(t);
                                })
                            });
                            return res;
                        });
                    },
                    // 是否开启批量
                    skuBatch(){
                        this.batch = this.batch == 0 ? 1 : 0;
                    },
                    cdnurl(url) {
                        if(url) return Fast.api.cdnurl(url);
                    }
                }
            })
            window.batchSet = function(field) {
                $('.wanl-' + field).val($('#batch-' + field).val())
            }
            // 完善寄件信息
            $(document).on("click", ".btn-send", function () {
                Backend.api.open('wanlshop/config/index/type/mailing/', __('完善寄件人信息'), {
                    callback:function(value){
                        console.log(value);
                    }
                });
            });
            // 完善退件信息
            $(document).on("click", ".btn-return", function () {
                Backend.api.open('wanlshop/config/index/type/return/', __('完善退货信息'), {
                    callback:function(value){
                        console.log(value);
                    }
                });
            });
            // 申请品牌
            $(document).on("click", ".btn-brand", function () {
                Backend.api.open('wanlshop/brand/add/', __('申请品牌'), {
                    callback:function(value){
                        console.log(value);
                    }
                });
            });
            // 新建运费模板
            $(document).on("click", ".btn-freight", function () {
                Backend.api.open('wanlshop/freight/add', __('新建运费模板'), {
                    callback:function(value){
                        console.log(value);
                    }
                });
            });
            // 新建店铺分类
            $(document).on("click", ".btn-shopsort", function () {
                Backend.api.open('wanlshop/shopsort/add', __('新建店铺分类'), {
                    callback:function(value){
                        console.log(value);
                    }
                });
            });
            // 打开方式
            if(Config.isdialog){
                Controller.api.bindevent();
            }else{
                Form.api.bindevent($("form[role=form]"), function (data, ret) {
                    setTimeout(function () {
                        location.href = Fast.api.fixurl('wanlshop.goods/index.html');
                    }, 500);
                });
            }
        },
        edit: function() {
            var vm = new Vue({
                el: '#app',
                data() {
                    return {
                        spu: Config.spu,
                        spuItem: Config.spuItem,
                        sku: Config.sku,
                        skuItem: Config.skuItem,
                        categoryId: Config.categoryId,
                        categoryList :Config.channelList,
                        categoryOne: null,
                        categoryTwo: null,
                        categoryThree: null,
                        categoryFour: null,
                        categoryFive: null,
                        attribute: Config.attribute,
                        attributeData: [],
                        batch: 0
                    }
                },
                mounted() {
                    this.categoryList.forEach((item,index)=>{
                        if (item.id == Config.categoryId ) {
                            this.categoryOne = index;
                        }else{
                            item.childlist.forEach((item1,index1)=>{
                                if (item1.id == Config.categoryId ) {
                                    this.categoryOne = index;
                                    this.categoryTwo = index1;
                                }else{
                                    item1.childlist.forEach((item2,index2)=>{
                                        if (item2.id == Config.categoryId ) {
                                            this.categoryOne = index;
                                            this.categoryTwo = index1;
                                            this.categoryThree = index2;
                                        }else{
                                            item2.childlist.forEach((item3,index3)=>{
                                                if (item3.id == Config.categoryId ) {
                                                    this.categoryOne = index;
                                                    this.categoryTwo = index1;
                                                    this.categoryThree = index2;
                                                    this.categoryFour = index3;
                                                }else{
                                                    item3.childlist.forEach((item4,index4)=>{
                                                        if (item4.id == Config.categoryId ) {
                                                            this.categoryOne = index;
                                                            this.categoryTwo = index1;
                                                            this.categoryThree = index2;
                                                            this.categoryFour = index3;
                                                            this.categoryFive = index4;
                                                        }
                                                    });
                                                }
                                            });
                                        }
                                    });
                                }
                            });
                        }
                    });
                    Fast.api.ajax("wanlshop.goods/attribute?id=" + this.categoryId, (data, ret) =>{
                        this.attributeData = data;
                        //返回false时将不再有右上角的操作成功的提示
                        return false;
                    });
                },
                methods: {
                    // 页面上传图片 1.1.9升级
                    changeImage(event, key){
                        let files = event.target.files[0]; //获取input的图片file值
                        require(['upload'], function (Upload) {
                            Upload.api.send(files, function (data, ret) {
                                // 1.0.8修复
                                if(vm.skuItem[key]){
                                    vm.skuItem[key]['thumbnail'] = data.url;
                                }else{
                                    Vue.set(vm.skuItem, key, {
                                        thumbnail: data.url
                                    })
                                }
                            });
                        });
                    },
                    getCategory(e){
                        if(e == 1){
                            this.categoryTwo = null;
                            this.categoryThree = null;
                            this.categoryFour = null;
                            this.categoryFive = null;
                        }
                        if(this.categoryOne != null){
                            this.categoryId = this.categoryList[this.categoryOne].id;
                        }
                        if(this.categoryTwo != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].id;
                        }
                        if(this.categoryThree != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].childlist[this.categoryThree].id;
                        }
                        if(this.categoryFour != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].childlist[this.categoryThree].childlist[this.categoryFour].id;
                        }
                        if(this.categoryFive != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].childlist[this.categoryThree].childlist[this.categoryFour].childlist[this.categoryFive].id;
                        }
                        // 查询类目属性
                        Fast.api.ajax("wanlshop.goods/attribute?id=" + this.categoryId, (data, ret) =>{
                            this.attributeData = data;
                            //返回false时将不再有右上角的操作成功的提示
                            return false;
                        });
                    },
                    // 添加属性
                    spuAdd(){
                        var str = this.$refs['specs-name'].value || ''
                        str = str.trim();
                        if (!str){
                            layer.msg("产品属性不能为空");
                            return
                        }
                        // 遍历
                        var arr = str.split(/\s+/);
                        for (var i=0;i<arr.length;i++)
                        {
                            this.spu.push(arr[i])
                        }
                        // 清空表单
                        this.$refs['specs-name'].value = ''
                    },
                    // 添加规格
                    skuAdd(index) {
                        console.log(this.spuItem);
                        var str = this.$refs['specs-name-' + index][0].value || ''
                        str = str.trim();
                        if (!str){
                            layer.msg("产品属性不能为空")
                            return
                        }
                        // 遍历
                        var arr = str.split(/\s+/);
                        for (var i=0;i<arr.length;i++)
                        {
                            if (this.spuItem[index]) {
                                this.spuItem[index].push(arr[i])
                            } else {
                                this.spuItem.push([arr[i]])
                            }
                        }
                        // 清空表单
                        this.$refs['specs-name-' + index][0].value = ""
                        this.skuCreate();
                    },


                    // 删除属性
                    spuRemove(key){
                        Vue.delete(vm.spuItem, key);
                        Vue.delete(vm.spu, key);
                        this.skuCreate();
                    },
                    // 删除规格
                    skuRemove(i,key){
                        Vue.delete(vm.spuItem[i], key);
                        this.skuCreate();
                    },
                    // 生成Sku
                    skuCreate() {
                        this.sku = this.skuDesign(this.spuItem)
                    },
                    skuDesign(array) {
                        if (array.length == 0) return []
                        if (array.length < 2) {
                            var res = []
                            array[0].forEach(function(v) {
                                res.push([v])
                            })
                            return res
                        }
                        return [].reduce.call(array, function(col, set) {
                            var res = [];
                            col.forEach(function(c) {
                                set.forEach(function(s) {
                                    var t = [].concat(Array.isArray(c) ? c : [c]);
                                    t.push(s);
                                    res.push(t);
                                })
                            });
                            return res;
                        });
                    },
                    // 是否开启批量
                    skuBatch(){
                        this.batch = this.batch == 0 ? 1 : 0;
                    },
                    cdnurl(url) {
                        if(url) return Fast.api.cdnurl(url);
                    }
                }
            })
            window.batchSet = function(field) {
                $('.wanl-' + field).val($('#batch-' + field).val())
            }
            // 申请品牌
            $(document).on("click", ".btn-brand", function () {
                Backend.api.open('wanlshop/brand/add/', __('申请品牌'), {
                    callback:function(value){
                        console.log(value);
                    }
                });
            });
            // 新建运费模板
            $(document).on("click", ".btn-freight", function () {
                Backend.api.open('wanlshop/freight/add', __('新建运费模板'), {
                    callback:function(value){
                        console.log(value);
                    }
                });
            });
            // 新建店铺分类
            $(document).on("click", ".btn-shopsort", function () {
                Backend.api.open('wanlshop/shopsort/add', __('新建店铺分类'), {
                    callback:function(value){
                        console.log(value);
                    }
                });
            });

            Controller.api.bindevent();
        },
        reuse: function() {
            var vm = new Vue({
                el: '#app',
                data() {
                    return {
                        spu: Config.spu,
                        spuItem: Config.spuItem,
                        sku: Config.sku,
                        skuItem: Config.skuItem,
                        categoryId: Config.categoryId,
                        categoryList :Config.channelList,
                        categoryOne: null,
                        categoryTwo: null,
                        categoryThree: null,
                        categoryFour: null,
                        categoryFive: null,
                        attribute: Config.attribute,
                        attributeData: [],
                        batch: 0
                    }
                },
                mounted() {
                    this.categoryList.forEach((item,index)=>{
                        if (item.id == Config.categoryId ) {
                            this.categoryOne = index;
                        }else{
                            item.childlist.forEach((item1,index1)=>{
                                if (item1.id == Config.categoryId ) {
                                    this.categoryOne = index;
                                    this.categoryTwo = index1;
                                }else{
                                    item1.childlist.forEach((item2,index2)=>{
                                        if (item2.id == Config.categoryId ) {
                                            this.categoryOne = index;
                                            this.categoryTwo = index1;
                                            this.categoryThree = index2;
                                        }else{
                                            item2.childlist.forEach((item3,index3)=>{
                                                if (item3.id == Config.categoryId ) {
                                                    this.categoryOne = index;
                                                    this.categoryTwo = index1;
                                                    this.categoryThree = index2;
                                                    this.categoryFour = index3;
                                                }else{
                                                    item3.childlist.forEach((item4,index4)=>{
                                                        if (item4.id == Config.categoryId ) {
                                                            this.categoryOne = index;
                                                            this.categoryTwo = index1;
                                                            this.categoryThree = index2;
                                                            this.categoryFour = index3;
                                                            this.categoryFive = index4;
                                                        }
                                                    });
                                                }
                                            });
                                        }
                                    });
                                }
                            });
                        }
                    });
                    Fast.api.ajax("wanlshop.goods/attribute?id=" + this.categoryId, (data, ret) =>{
                        this.attributeData = data;
                        //返回false时将不再有右上角的操作成功的提示
                        return false;
                    });
                },
                methods: {
                    // 页面上传图片 1.1.9升级
                    changeImage(event, key){
                        let files = event.target.files[0]; //获取input的图片file值
                        require(['upload'], function (Upload) {
                            Upload.api.send(files, function (data, ret) {
                                // 1.0.8修复
                                if(vm.skuItem[key]){
                                    vm.skuItem[key]['thumbnail'] = data.url;
                                }else{
                                    Vue.set(vm.skuItem, key, {
                                        thumbnail: data.url
                                    })
                                }
                            });
                        });
                    },
                    getCategory(e){
                        if(e == 1){
                            this.categoryTwo = null;
                            this.categoryThree = null;
                            this.categoryFour = null;
                            this.categoryFive = null;
                        }
                        if(this.categoryOne != null){
                            this.categoryId = this.categoryList[this.categoryOne].id;
                        }
                        if(this.categoryTwo != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].id;
                        }
                        if(this.categoryThree != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].childlist[this.categoryThree].id;
                        }
                        if(this.categoryFour != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].childlist[this.categoryThree].childlist[this.categoryFour].id;
                        }
                        if(this.categoryFive != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].childlist[this.categoryThree].childlist[this.categoryFour].childlist[this.categoryFive].id;
                        }
                        // 查询类目属性
                        Fast.api.ajax("wanlshop.goods/attribute?id=" + this.categoryId, (data, ret) =>{
                            this.attributeData = data;
                            //返回false时将不再有右上角的操作成功的提示
                            return false;
                        });
                    },
                    // 添加属性
                    spuAdd(){
                        var str = this.$refs['specs-name'].value || ''
                        str = str.trim();
                        if (!str){
                            layer.msg("产品属性不能为空");
                            return
                        }
                        // 遍历
                        var arr = str.split(/\s+/);
                        for (var i=0;i<arr.length;i++)
                        {
                            this.spu.push(arr[i])
                        }
                        // 清空表单
                        this.$refs['specs-name'].value = ''
                    },
                    // 添加规格
                    skuAdd(index) {
                        console.log(this.spuItem);
                        var str = this.$refs['specs-name-' + index][0].value || ''
                        str = str.trim();
                        if (!str){
                            layer.msg("产品属性不能为空")
                            return
                        }
                        // 遍历
                        var arr = str.split(/\s+/);
                        for (var i=0;i<arr.length;i++)
                        {
                            if (this.spuItem[index]) {
                                this.spuItem[index].push(arr[i])
                            } else {
                                this.spuItem.push([arr[i]])
                            }
                        }
                        // 清空表单
                        this.$refs['specs-name-' + index][0].value = ""
                        this.skuCreate();
                    },


                    // 删除属性
                    spuRemove(key){
                        Vue.delete(vm.spuItem, key);
                        Vue.delete(vm.spu, key);
                        this.skuCreate();
                    },
                    // 删除规格
                    skuRemove(i,key){
                        Vue.delete(vm.spuItem[i], key);
                        this.skuCreate();
                    },
                    // 生成Sku
                    skuCreate() {
                        this.sku = this.skuDesign(this.spuItem)
                    },
                    skuDesign(array) {
                        if (array.length == 0) return []
                        if (array.length < 2) {
                            var res = []
                            array[0].forEach(function(v) {
                                res.push([v])
                            })
                            return res
                        }
                        return [].reduce.call(array, function(col, set) {
                            var res = [];
                            col.forEach(function(c) {
                                set.forEach(function(s) {
                                    var t = [].concat(Array.isArray(c) ? c : [c]);
                                    t.push(s);
                                    res.push(t);
                                })
                            });
                            return res;
                        });
                    },
                    // 是否开启批量
                    skuBatch(){
                        this.batch = this.batch == 0 ? 1 : 0;
                    },
                    cdnurl(url) {
                        if(url) return Fast.api.cdnurl(url);
                    }
                }
            })
            window.batchSet = function(field) {
                $('.wanl-' + field).val($('#batch-' + field).val())
            }
            // 申请品牌
            $(document).on("click", ".btn-brand", function () {
                Backend.api.open('wanlshop/brand/add/', __('申请品牌'), {
                    callback:function(value){
                        console.log(value);
                    }
                });
            });
            // 新建运费模板
            $(document).on("click", ".btn-freight", function () {
                Backend.api.open('wanlshop/freight/add', __('新建运费模板'), {
                    callback:function(value){
                        console.log(value);
                    }
                });
            });
            // 新建店铺分类
            $(document).on("click", ".btn-shopsort", function () {
                Backend.api.open('wanlshop/shopsort/add', __('新建店铺分类'), {
                    callback:function(value){
                        console.log(value);
                    }
                });
            });

            Controller.api.bindevent();
        },
        resubmit: function () {
            var goods_id = Config.goods_id;
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'wanlshop/goods/resubmit?ids=' + goods_id +"&"+ location.search,
                    // table: 'wanlshop_shop',
                }
            });

            var table = $("#table");

            $(".btn-add").data("area", ["100%", "100%"]);

            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                    $(".btn-editone").data("area", ["100%", "100%"]);
             });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                fixedColumns: true,
                fixedRightNumber: 1,
                Search:true,
                commonSearch:true,
                searchFormVisible:true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'),visible:false, operate: false},
                        {field: 'code', title: __('店铺编号'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'type', title: __('商家分类'), searchList: {"0":__('直营店'),"1":__('加盟店'),"2":__('社区单店')}, operate: false,formatter: Table.api.formatter.normal},
                        {field: 'shopname', title: __('商家名称'), operate: 'LIKE'},
                        {field: 'person', title: __('联系人'), operate: 'LIKE', operate: false},
                        {field: 'telephone', title: __('联系方式'), operate: 'LIKE', operate: false},
                        {field: 'city', title: __('所属地区'), operate: 'LIKE', operate: false},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime, operate: false},
                        {field: 'status', title: __('Status'), searchList: {"normal":__('营业中'),"hidden":__('下线')}, formatter: Table.api.formatter.status, operate: false}
                    ]
                ]
            });

            $("button[type='submit']").css("background-color","red");
            $("button[type='submit']").css("border-color","red");

            //保存设置
            $(document).on("click", ".choose-shop", function () {
                var ids = Table.api.selectedids(table);
                if (ids.length == 0) {
                    layer.msg("请选择要铺设的店铺！");
                }
                Fast.api.ajax({
                    url: 'wanlshop/goods/savegoodsshop',
                    type: 'post',
                    loading: false,
                    data: {
                        ids: ids,
                        goods_id: goods_id
                    }
                }, function (data, ret) {
                    if (ret.code == 1) {
                        Layer.open({
                            title:'提示',
                            type: 1, 
                            area: ['280px', '180px'],
                            content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;">铺设成功</p>',
                            btn: ['确定'], // 弹窗按钮
                            btnAlign:"c",
                            yes: function(index, layero){
                                // 点击确定按钮后的回调函数
                                // index是弹窗的索引，layero是弹窗的DOM对象
                                // Layer.close(index);
                                parent.Layer.closeAll();
                                parent.$("a.btn-refresh").trigger("click");
                            }
                        });
                    }else{
                        Layer.open({
                            title:'提示',
                            type: 1, 
                            area: ['280px', '180px'],
                            content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;">操作失败，请售后重试！</p>',
                            btn: ['确定'], // 弹窗按钮
                            btnAlign:"c",
                            yes: function(index, layero){
                                // 点击确定按钮后的回调函数
                                // index是弹窗的索引，layero是弹窗的DOM对象
                                // Layer.close(index);
                                parent.Layer.closeAll();
                                parent.$("a.btn-refresh").trigger("click");
                            }
                        });
                    }
                    return false;
                });
            });
            
            
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        batch: function () {
            var goods_id = Config.goods_id;
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'wanlshop/goods/batch?ids=' + goods_id +"&"+ location.search,
                    // table: 'wanlshop_shop',
                }
            });

            var table = $("#table");

            $(".btn-add").data("area", ["100%", "100%"]);

            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                    $(".btn-editone").data("area", ["100%", "100%"]);
             });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                // sortName: 'weigh',
                fixedColumns: true,
                fixedRightNumber: 1,
                searchFormVisible:true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'),visible:false, operate: false},
                        {field: 'code', title: __('店铺编号'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'type', title: __('商家分类'), searchList: {"0":__('直营店'),"1":__('加盟店'),"2":__('社区单店')}, operate: false,formatter: Table.api.formatter.normal},
                        {field: 'shopname', title: __('商家名称'), operate: 'LIKE'},
                        {field: 'person', title: __('联系人'), operate: 'LIKE', operate: false},
                        {field: 'telephone', title: __('联系方式'), operate: 'LIKE', operate: false},
                        {field: 'city', title: __('所属地区'), operate: 'LIKE', operate: false},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime, operate: false},
                        {field: 'status', title: __('Status'), searchList: {"normal":__('营业中'),"hidden":__('下线')}, formatter: Table.api.formatter.status, operate: false}
                    ]
                ]
            });

            $("button[type='submit']").css("background-color","red");
            $("button[type='submit']").css("border-color","red");

            //保存设置
            $(document).on("click", ".choose-shop", function () {
                var ids = Table.api.selectedids(table);
                if (ids.length == 0) {
                    layer.msg("请选择要设置的店铺！");
                }
                Fast.api.ajax({
                    url: 'wanlshop/goods/batchdelistingshop',
                    type: 'post',
                    loading: false,
                    data: {
                        ids: ids,
                        goods_id: goods_id
                    }
                }, function (data, ret) {
                    if (ret.code == 1) {
                        Layer.open({
                            title:'提示',
                            type: 1, 
                            area: ['280px', '180px'],
                            content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;">下架成功</p>',
                            btn: ['确定'], // 弹窗按钮
                            btnAlign:"c",
                            yes: function(index, layero){
                                // 点击确定按钮后的回调函数
                                // index是弹窗的索引，layero是弹窗的DOM对象
                                // Layer.close(index);
                                parent.Layer.closeAll();
                                parent.$("a.btn-refresh").trigger("click");
                            }
                        });
                    }else{
                        Layer.open({
                            title:'提示',
                            type: 1, 
                            area: ['280px', '180px'],
                            content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;">操作失败，请售后重试！</p>',
                            btn: ['确定'], // 弹窗按钮
                            btnAlign:"c",
                            yes: function(index, layero){
                                // 点击确定按钮后的回调函数
                                // index是弹窗的索引，layero是弹窗的DOM对象
                                // Layer.close(index);
                                parent.Layer.closeAll();
                                parent.$("a.btn-refresh").trigger("click");
                            }
                        });
                    }
                    return false;
                });
            });
            
            
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        topgoods: function() {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'wanlshop/goods/topgoods' + location.search,
                    add_url: 'wanlshop/goods/add',
                   // edit_url: 'wanlshop/goods/edit',
                   // del_url: 'wanlshop/goods/del',
                    multi_url: 'wanlshop/goods/multi',
                    resubmit_url: 'wanlshop/goods/resubmit',
                    dragsort_url: "",
                    table: 'wanlshop_goods',
                }
            });

            var table = $("#table");
            $(".btn-add").data("area", ["100%", "100%"]);

            $(document).on("click", ".goods-shop-type-item", function () {
                $(".active-type").removeClass('active-type');
                $(this).addClass('active-type');
                window.location =  $(this).data('url');
            });
            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                    $(".btn-editone").data("area", ["100%", "100%"]);
             });

            table.on('post-common-search.bs.table', function (event, table) {
                $('ul.nav-tabs li a[data-value="normal"]').trigger('click');
                $(".form-commonsearch select[name=status]").val("normal");
            });
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                fixedColumns: true,
                fixedRightNumber: 1,
                Search:true,
                commonSearch:true,
                searchFormVisible:true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id',title: __('Id') ,operate: false,visible:false},
                        {field: 'code',title: __('商品编号') ,operate: 'like'},
                        {field: 'title',title: __('Title'),operate: 'like'},
                        {field: 'category.name', title: __('商品分类'), formatter: Table.api.formatter.search},
                        {field: 'price',title: __('价格(元)'),operate: false},
                        {field: 'channel',title: __('渠道'),searchList: {"0": __('All'),"1": __('线上'),"2": __('线下')},formatter: Table.api.formatter.status,operate: false},
                       
                        // {field: 'operate',title: __('Operate'),table: table, events: Table.api.events.operate,formatter: Table.api.formatter.operate}
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            buttons :[
                                {
                                    name: 'detail',
                                    text: '商品详情',
                                    title: '商品详情',
                                    icon: '',
                                    extend: 'data-area=\'["80%", "80%"]\'',
                                    classname: 'btn btn-xs btn-danger btn-dialog',
                                    url: "wanlshop/goods/detail",
                                },
                                {
                                    name: 'resubmittoshop',
                                    text: '添加到本店',
                                    title: '添加到本店',
                                    icon: '',
                                    extend: 'data-area=\'["80%", "80%"]\'',
                                    classname: 'btn btn-xs btn-danger btn-ajax',
                                    url: "wanlshop/goods/resubmittoshop",
                                    refresh: true,
                                    hidden:function(row){
                                        if(row.already_copy == 1){
                                            return true;
                                        }else{
                                            return false;
                                        }
                                    },
                                },
                            ],
                            callback: function (data) {
                                table.bootstrapTable('refresh', {});
                                return false;
                            },
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        detail: function() {
            var vm = new Vue({
                el: '#app',
                data() {
                    return {
                        spu: Config.spu,
                        spuItem: Config.spuItem,
                        sku: Config.sku,
                        skuItem: Config.skuItem,
                        categoryId: Config.categoryId,
                        categoryList :Config.channelList,
                        categoryOne: null,
                        categoryTwo: null,
                        categoryThree: null,
                        categoryFour: null,
                        categoryFive: null,
                        attribute: Config.attribute,
                        attributeData: [],
                        batch: 0
                    }
                },
                mounted() {
                    this.categoryList.forEach((item,index)=>{
                        if (item.id == Config.categoryId ) {
                            this.categoryOne = index;
                        }else{
                            item.childlist.forEach((item1,index1)=>{
                                if (item1.id == Config.categoryId ) {
                                    this.categoryOne = index;
                                    this.categoryTwo = index1;
                                }else{
                                    item1.childlist.forEach((item2,index2)=>{
                                        if (item2.id == Config.categoryId ) {
                                            this.categoryOne = index;
                                            this.categoryTwo = index1;
                                            this.categoryThree = index2;
                                        }else{
                                            item2.childlist.forEach((item3,index3)=>{
                                                if (item3.id == Config.categoryId ) {
                                                    this.categoryOne = index;
                                                    this.categoryTwo = index1;
                                                    this.categoryThree = index2;
                                                    this.categoryFour = index3;
                                                }else{
                                                    item3.childlist.forEach((item4,index4)=>{
                                                        if (item4.id == Config.categoryId ) {
                                                            this.categoryOne = index;
                                                            this.categoryTwo = index1;
                                                            this.categoryThree = index2;
                                                            this.categoryFour = index3;
                                                            this.categoryFive = index4;
                                                        }
                                                    });
                                                }
                                            });
                                        }
                                    });
                                }
                            });
                        }
                    });
                    Fast.api.ajax("wanlshop.goods/attribute?id=" + this.categoryId, (data, ret) =>{
                        this.attributeData = data;
                        //返回false时将不再有右上角的操作成功的提示
                        return false;
                    });
                },
                methods: {
                    // 页面上传图片 1.1.9升级
                    changeImage(event, key){
                        let files = event.target.files[0]; //获取input的图片file值
                        require(['upload'], function (Upload) {
                            Upload.api.send(files, function (data, ret) {
                                // 1.0.8修复
                                if(vm.skuItem[key]){
                                    vm.skuItem[key]['thumbnail'] = data.url;
                                }else{
                                    Vue.set(vm.skuItem, key, {
                                        thumbnail: data.url
                                    })
                                }
                            });
                        });
                    },
                    getCategory(e){
                        if(e == 1){
                            this.categoryTwo = null;
                            this.categoryThree = null;
                            this.categoryFour = null;
                            this.categoryFive = null;
                        }
                        if(this.categoryOne != null){
                            this.categoryId = this.categoryList[this.categoryOne].id;
                        }
                        if(this.categoryTwo != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].id;
                        }
                        if(this.categoryThree != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].childlist[this.categoryThree].id;
                        }
                        if(this.categoryFour != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].childlist[this.categoryThree].childlist[this.categoryFour].id;
                        }
                        if(this.categoryFive != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].childlist[this.categoryThree].childlist[this.categoryFour].childlist[this.categoryFive].id;
                        }
                        // 查询类目属性
                        Fast.api.ajax("wanlshop.goods/attribute?id=" + this.categoryId, (data, ret) =>{
                            this.attributeData = data;
                            //返回false时将不再有右上角的操作成功的提示
                            return false;
                        });
                    },
                    // 添加属性
                    spuAdd(){
                        var str = this.$refs['specs-name'].value || ''
                        str = str.trim();
                        if (!str){
                            layer.msg("产品属性不能为空");
                            return
                        }
                        // 遍历
                        var arr = str.split(/\s+/);
                        for (var i=0;i<arr.length;i++)
                        {
                            this.spu.push(arr[i])
                        }
                        // 清空表单
                        this.$refs['specs-name'].value = ''
                    },
                    // 添加规格
                    skuAdd(index) {
                        console.log(this.spuItem);
                        var str = this.$refs['specs-name-' + index][0].value || ''
                        str = str.trim();
                        if (!str){
                            layer.msg("产品属性不能为空")
                            return
                        }
                        // 遍历
                        var arr = str.split(/\s+/);
                        for (var i=0;i<arr.length;i++)
                        {
                            if (this.spuItem[index]) {
                                this.spuItem[index].push(arr[i])
                            } else {
                                this.spuItem.push([arr[i]])
                            }
                        }
                        // 清空表单
                        this.$refs['specs-name-' + index][0].value = ""
                        this.skuCreate();
                    },


                    // 删除属性
                    spuRemove(key){
                        Vue.delete(vm.spuItem, key);
                        Vue.delete(vm.spu, key);
                        this.skuCreate();
                    },
                    // 删除规格
                    skuRemove(i,key){
                        Vue.delete(vm.spuItem[i], key);
                        this.skuCreate();
                    },
                    // 生成Sku
                    skuCreate() {
                        this.sku = this.skuDesign(this.spuItem)
                    },
                    skuDesign(array) {
                        if (array.length == 0) return []
                        if (array.length < 2) {
                            var res = []
                            array[0].forEach(function(v) {
                                res.push([v])
                            })
                            return res
                        }
                        return [].reduce.call(array, function(col, set) {
                            var res = [];
                            col.forEach(function(c) {
                                set.forEach(function(s) {
                                    var t = [].concat(Array.isArray(c) ? c : [c]);
                                    t.push(s);
                                    res.push(t);
                                })
                            });
                            return res;
                        });
                    },
                    // 是否开启批量
                    skuBatch(){
                        this.batch = this.batch == 0 ? 1 : 0;
                    },
                    cdnurl(url) {
                        if(url) return Fast.api.cdnurl(url);
                    }
                }
            })
            window.batchSet = function(field) {
                $('.wanl-' + field).val($('#batch-' + field).val())
            }
            // 申请品牌
            $(document).on("click", ".btn-brand", function () {
                Backend.api.open('wanlshop/brand/add/', __('申请品牌'), {
                    callback:function(value){
                        console.log(value);
                    }
                });
            });
            // 新建运费模板
            $(document).on("click", ".btn-freight", function () {
                Backend.api.open('wanlshop/freight/add', __('新建运费模板'), {
                    callback:function(value){
                        console.log(value);
                    }
                });
            });
            // 新建店铺分类
            $(document).on("click", ".btn-shopsort", function () {
                Backend.api.open('wanlshop/shopsort/add', __('新建店铺分类'), {
                    callback:function(value){
                        console.log(value);
                    }
                });
            });
            $(document).ready(function() {
                $(".btn-trash").hide();
                $(".show-img-detail").hide();
                $(".c-freight_id_text").attr('disabled', 'disabled');
                $("input[type=number],input[type=text]").attr('disabled', 'disabled');
                $('textarea').attr('readonly', 'readonly');
                $('span[data-role="remove"]').hide();
            });
            Controller.api.bindevent();
        },
        api: {
            bindevent: function() {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
